有限狀態機 - Finite-state machine
其中又可分為Mealy機和Moore機
所謂的有限狀態機對於工科的孩子來說大概最直觀的就是真值表吧(是嗎?)
當狀態為A條件為A時將指到狀態B
條件/狀態 | 狀態A | 狀態B
------------- | -------------
條件A | 狀態B | ...
條件B | ... | 狀態B
其中又以下圖為例
這邊以一個實際案例來模擬有限狀態機的行為
輸入一串隨意文字 以空白為間隔 以.為結束
以rate R2D2 48 2 time 5566.為例
rate會判為identifier
R2D2會判為identifier
48會判為number
2會判為number
time會判為identifier
5566會判為number
2t會判為Error
t#會判為Error
而實際轉換成C是將各個條件包成Function
int build_num(){
char c;
int state=1;
do{
scanf("%c",&c);
if(c>='0' && c<='9'){
printf("%c",c);
state=1;
}
else if(c==' '){
return state;
}
else{
printf("%c",c);
state=build_invalid();
return 3;
}
}while(c!=' ');
return state;
}
int build_invalid(){
char c;
int state=3;
do{
scanf("%c",&c);
if(c!=' '){
printf("%c",c);
}
}while(c!=' ');
return state;
}
int build_id(){
char c;
int state=2;
do{
scanf("%c",&c);
if(c>='a'&&c<='z'|| c>='A'&&c<='Z'){
printf("%c",c);
}
else if(c>='0'&&c<='9'){
printf("%c",c);
}
else if(c=='_'){
printf("%c",c);
}
else if(c==' '){
return 2;
}
else{
printf("%c",c);
build_invalid();
return 3;
}
}while(c!=' ');
return state;
}
int main(){
char c;
int state=0;
do{
scanf("%c",&c);
if(c>='0' && c<='9'){
printf("%c",c);
state=build_num();
if(state == 1){
printf(" - Number\n");
}
else if(state == 3){
printf(" - Invalid\n");
}
}
else if(c>='a' && c<='z' || c>='A' && c<='Z'){
printf("%c",c);
state=build_id();
if(state == 2){
printf(" - Identifier\n");
}
else if(state == 3){
printf(" - Invalid\n");
}
}
}while(c!='.');
}